import Taro from "@tarojs/taro"

/**
 * @name randomStr
 * @desc 随机字符串
 * @param {Number} len - 字符串长度
 */
function randomStr(len = 16) {
    const string = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    const l = string.length
    let str = ""
    for (let i = 0; i < len; i++) {
        const index = Math.floor((Math.random() * 100 * l) % l)
        str += string[index]
    }
    return str
}

/**
 * @param {Object|Number} date 日期对象|时间戳
 * @param {String} formate 日期格式 'yyy'-年份,'mmm'-月份,'ddd'-日期,'www'-星期,'hh'-小时,'mm'-分钟,'ss'-秒
 */

function dateFormate(date, formate = "yyy-mmm-ddd 星期www hh:mm:ss") {
    let objDate = null
    if (date instanceof Date) {
        objDate = date
    } else if (typeof date === "number") {
        objDate = new Date(date)
    } else {
        objDate = new Date()
    }

    const d = {
        yyy: objDate.getFullYear(),
        mmm: objDate.getMonth() + 1,
        ddd: objDate.getDate(),
        www: ["日", "一", "二", "三", "四", "五", "六"][objDate.getDay()],
        hh: objDate.getHours(),
        mm: objDate.getMinutes(),
        ss: objDate.getSeconds()
    }
    const zero = num => (num > 9 ? num : `0${num}`)
    let formateStr = formate
    for (const key in d) {
        if (d.hasOwnProperty(key)) {
            const reg = new RegExp(`${key}`)
            formateStr = formateStr.replace(reg, key === "www" ? d[key] : zero(d[key]))
        }
    }
    return formateStr
}

/**
 * @param {Number} num - 要处理的数值
 * @param {Number} count - 小数点后保留的位数
 * @param {String} type - 小数位舍入方式,可选['round','ceil','floor']
 */
function numberFixed(num = 0, { count = 2, type = "round" } = {}) {
    const power = Math.pow(10, count)
    return Math[type](num * power) / power
}

/**
 * @desc 判断是否需要添加底部边距
 */
const models = ["iPhone X"]
let shouldBottom = false
Taro.getSystemInfo().then(res => {
    for (let i = 0; i < models.length; i++) {
        if (res.model.indexOf(models[i]) !== -1) {
            console.log("sys", res)
            shouldBottom = true
            return
        }
    }
})

export { randomStr, dateFormate, numberFixed, shouldBottom }
